package com.oriole.api.module.sys.controller;


import com.oriole.api.module.sys.service.ISysDeptService;
import com.oriole.api.module.sys.service.ISysRoleService;
import com.oriole.api.module.sys.service.ISysUserService;
import com.oriole.common.constant.Constants;
import com.oriole.common.constant.ResultModel;
import com.oriole.common.constant.ResultStatus;
import com.oriole.common.controller.OriolePage;
import com.oriole.common.controller.PageableUtil;
import com.oriole.common.exception.OrioleRuntimeException;
import com.oriole.common.util.ConvertUtil;
import com.oriole.common.util.PasswordEncoderUtil;
import com.oriole.entity.sys.SysDept;
import com.oriole.entity.sys.SysRole;
import com.oriole.entity.sys.SysUser;
import com.oriole.entity.vo.SysUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 系统用户表 前端控制器
 * </p>
 *
 * @author hautxxxyzjk@163.com
 * @since 2020-03-10
 */
@Api(value = "ApiSysUserController", tags = {"系统用户-ApiSysUserController"})
@RestController
@RequestMapping("/api/sysUser")
public class ApiSysUserController {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private ISysRoleService sysRoleService;

    @ApiOperation(value = "系统用户-保存用户信息")
    @PostMapping("/save")
    public ResultModel<SysUser> save(@ApiParam(name = "sysUser", value = "用户信息", required = true) @Valid @RequestBody SysUser sysUser) {
        sysUser.setPassword(PasswordEncoderUtil.encodeByBCrypt(sysUser.getPassword()));
        SysDept sysDept = sysDeptService.findById(sysUser.getSysDept().getId());
        sysUser.setSysDept(sysDept);
        SysUser result = sysUserService.save(sysUser);
        result.setPassword("");
        return ResultModel.success(result);
    }

    @ApiOperation(value = "系统用户-修改用户信息")
    @PutMapping("/update")
    public ResultModel<SysUser> update(@ApiParam(name = "sysUser", value = "用户信息", required = true) @Valid @RequestBody SysUser sysUser) {
        if (StringUtils.isBlank(sysUser.getId().toString())) {
            throw new OrioleRuntimeException(Constants.ID_CANNOT_BE_NULL);
        }
        // 持久化对象
        SysUser persistentSysUser = sysUserService.findById(sysUser.getId());
        BeanUtils.copyProperties(sysUser, persistentSysUser, "password", "createdBy", "createdDate");
        SysDept sysDept = sysDeptService.findById(sysUser.getSysDept().getId());
        persistentSysUser.setSysDept(sysDept);
        SysUser result = sysUserService.save(persistentSysUser);

        return ResultModel.success(result);
    }

    @ApiOperation(value = "系统用户-修改用户信息-基本资料")
    @PutMapping("/updateProfile")
    public ResultModel<SysUser> updateProfile(@ApiParam(name = "sysUser", value = "用户信息", required = true) @Valid @RequestBody SysUser sysUser) {
        if (StringUtils.isBlank(sysUser.getId().toString())) {
            throw new OrioleRuntimeException(Constants.ID_CANNOT_BE_NULL);
        }
        // 持久化对象
        SysUser persistentSysUser = sysUserService.findById(sysUser.getId());
        persistentSysUser.setAvatar(sysUser.getAvatar());
        SysUser result = sysUserService.save(persistentSysUser);

        return ResultModel.success(result);
    }

    @ApiOperation(value = "系统用户-删除用户信息")
    @DeleteMapping("/delete/{id}")
    public ResultModel<SysUser> delete(@ApiParam(name = "id", value = "主键ID", required = true) @PathVariable("id") Long id) {
        sysUserService.deleteById(id);
        return new ResultModel<>(ResultStatus.SUCCESS);
    }

    @ApiOperation(value = "系统用户-批量删除用户信息")
    @DeleteMapping("/deleteBatchByIds")
    public ResultModel<SysUser> deleteBatchByIds(List<Long> ids) {
        sysUserService.deleteBatchByIds(ids);
        return new ResultModel<>(ResultStatus.SUCCESS);
    }

    @ApiOperation(value = "系统用户-获取用户列表")
    @GetMapping("/findAll")
    public ResultModel<List<SysUser>> findAll() {
        List<SysUser> users = sysUserService.findAll();
        return ResultModel.success(users);
    }

    @ApiOperation(value = "系统用户-获取分页用户列表")
    @GetMapping("/findPage")
    public ResultModel<Object> findPage(@RequestBody OriolePage oriolePage) {
        Pageable pageable = PageableUtil.getPageable(oriolePage);
        Page<SysUser> page = sysUserService.findPage(oriolePage.getCondition(), pageable);
        return ResultModel.success(page);
    }

    @ApiOperation(value = "系统用户-根据用户名获取用户信息")
    @GetMapping("/findByUsername")
    public ResultModel<SysUser> findByUsername(@ApiParam(name = "username", value = "用户名", required = true) @RequestParam("username") String username) {
        SysUser sysUser = sysUserService.findByUsername(username);
        return ResultModel.success(sysUser);
    }

    @ApiOperation(value = "系统用户-根据ID获取用户信息")
    @GetMapping("/find/{id}")
    public ResultModel<SysUser> findById(@ApiParam(name = "id", value = "主键ID", required = true) @PathVariable("id") Long id) {
        SysUser sysUser = sysUserService.findById(id);
        return ResultModel.success(sysUser);
    }

    @ApiOperation(value = "系统用户-根据ID获取用户信息")
    @GetMapping("/findBasicInfo/{id}")
    public ResultModel<SysUserVo> findBasicInfoById(@ApiParam(name = "id", value = "主键ID", required = true) @PathVariable("id") Long id) {
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(sysUserService.findById(id), sysUserVo);
        return ResultModel.success(sysUserVo);
    }

    @ApiOperation(value = "系统用户-用户设置角色")
    @PutMapping("/setSysRole")
    public ResultModel<SysUser> setSysRole(@RequestParam String sysRoleIds, @RequestParam Long sysUserId) {
        SysUser sysUser = sysUserService.findById(sysUserId);
        Long[] roleIds = ConvertUtil.toLongArray(sysRoleIds);
        Set<SysRole> sysRoles = new LinkedHashSet<>();
        for (long roleId : roleIds) {
            SysRole sysRole = sysRoleService.findById(roleId);
            sysRoles.add(sysRole);
        }
        sysUser.setSysRoles(sysRoles);
        SysUser result = sysUserService.save(sysUser);
        return ResultModel.success(result);
    }

}

